package cn.itcast.lucene;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.search.*;
import org.apache.lucene.store.FSDirectory;
import org.junit.Test;

import java.io.File;

public class QueryIndex {

    /**
     * 搜索索引库内容
     */
    @Test
    public void queryIndexTest() throws Exception {

        //获取读取索引库对象
        DirectoryReader reader = DirectoryReader.open(FSDirectory.open(new File("F:\\index92")));

        //获取查询索引库对象
        IndexSearcher indexSearcher = new IndexSearcher(reader);

        //查询索引库所有文档对象
        //Query query = new MatchAllDocsQuery();
        //基于词条查询  搜索内容是词条时，才能查询到搜索结果
        //Query query = new TermQuery(new Term("fileName","传智"));
        //模糊查询  * ：任意多个  ?：任意一个
       // Query query = new WildcardQuery(new Term("fileName","传智??"));
        //相似度匹配查询 往往针对英文  参数二：最大编辑数 [0,2]  修改搜索的词条几次后，可以还原成索引库词条
        //lnceue ----> luceue ---> lucene
        //Query query = new FuzzyQuery(new Term("fileName","lucene"));
        //参数1：查询的域，参数2：起始字节数值，参数3：结束字节数值，参数4：包含起始，参数5：包含结束
        Query query = NumericRangeQuery.newLongRange("fileSize",0L,50L,true,true);

       /* BooleanQuery query = new BooleanQuery();
        TermQuery query1 = new TermQuery(new Term("fileName", "传智播客"));
        TermQuery query2 = new TermQuery(new Term("fileName", "阴阳师"));

        //MUST必须满足 SHOULD可以满足 MUST_NOT一定不满足
        query.add(query1, BooleanClause.Occur.MUST);
        query.add(query2, BooleanClause.Occur.MUST_NOT);*/

       //单字段域解析
       /* String queryStr = "传智播客是一家培训机构lucene";
        //ik分词器分词
        Analyzer analyzer = new IKAnalyzer();
        QueryParser parser = new QueryParser("fileName", analyzer);
        Query query = parser.parse(queryStr);*/

        //多字段域解析
       /* String queryStr = "传智播客是一家培训机构lucene";
        //ik分词器分词
        Analyzer analyzer = new IKAnalyzer();
        MultiFieldQueryParser parser = new MultiFieldQueryParser(new String[]{"fileName","fileContent"}, analyzer);
        Query query = parser.parse(queryStr);*/

        // 参数一：查询对象  参数二：要显示查询条数
        TopDocs topDocs = indexSearcher.search(query, 10);
        System.out.println("满足查询条件的总条件："+topDocs.totalHits);

        ScoreDoc[] scoreDocs = topDocs.scoreDocs;
        for (ScoreDoc scoreDoc : scoreDocs) {
            //获取文档id
            int docId = scoreDoc.doc;
            //基于文档id查询文档数据
            Document document = indexSearcher.doc(docId);
            //文档内容
            System.out.println("名称:"+document.getField("fileName"));
            System.out.println("内容"+document.getField("fileContent"));
            System.out.println("大小"+document.getField("fileSize"));
            System.out.println("路径"+document.getField("filePath"));
        }

    }
}
